package com.landun.market.pojo.enums;

import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author jiang.chuan
 * @date 2018-05-11
 */
public enum Gender implements IEnumType {
    UNKNOWN(0, "未知"),
    MALE(1, "男"),
    FEMALE(2, "女");
    private final static Map<Integer, Gender> BY_CODE_MAP
            = Arrays.stream(Gender.values()).collect(Collectors.toMap(Gender::code, code -> code));

    private final static Map<String, Gender> BY_NAME_MAP
            = Arrays.stream(Gender.values()).collect(Collectors.toMap(code -> code.name().toLowerCase(), code -> code));


    private final int code;
    private final String desc;

    /**
     * @param code 代码
     * @param desc 描述
     */
    Gender(final int code, final String desc) {
        this.code = code;
        this.desc = desc;
    }

    @Override
    public int code() {
        return this.code;
    }

    @Override
    public String desc() {
        return this.desc;
    }

    /**
     * @param code 代码
     * @return 转换出来的状态码
     */
    public static Gender parse(Integer code) {
        return BY_CODE_MAP.get(code);
    }

    public static Gender parse(Integer code, Gender defaultGender) {
        return BY_CODE_MAP.getOrDefault(code, defaultGender);
    }

    /**
     * @param name 名字
     * @return 转换出来的状态码
     */
    public static Gender parse(String name) {
        if (StringUtils.isBlank(name)) {
            return null;
        }
        return BY_NAME_MAP.get(name.trim().toLowerCase());
    }

    public static Gender parse(String name, Gender defaultGender) {
        if (StringUtils.isBlank(name)) {
            return defaultGender;
        }
        return BY_NAME_MAP.getOrDefault(name.trim().toLowerCase(), defaultGender);
    }
}

